import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { workAPI, userAPI } from '../services/api';
import './styles.css';

function HomePage() {
  const [articles, setArticles] = useState([]);
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [userData, setUserData] = useState(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [searchType, setSearchType] = useState('articles'); // 'articles' 或 'users'
  const [isSearching, setIsSearching] = useState(false);
  const [searchResults, setSearchResults] = useState(null);
  
  const navigate = useNavigate();

  // 在组件加载时获取文章列表和检查登录状态
  useEffect(() => {
    fetchArticles();
    checkLoginStatus();
  }, []);
  const workPost={
    workId: "",
    createdAt: "",
    userId: "13",
    context: "",
    title: "",
    description: "",
    type: 1
  }
  // 获取所有文章信息
  const fetchArticles = async () => {
    try {
      setLoading(true);
      // 发送空对象作为请求体，获取所有文章
      const response = await workAPI.searchWorks(workPost);
      
      if (response && response.result) {
        setArticles(response.result || []);
      } else {
        setArticles([]);
      }
    } catch (err) {
      console.error('获取文章失败:', err);
      setError('获取文章列表时发生错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 格式化日期显示
  const formatDate = (dateString) => {
    if (!dateString) return '未知日期';
    
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', { 
      year: 'numeric', 
      month: '2-digit', 
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // 检查用户登录状态
  const checkLoginStatus = () => {
    const isLoggedInStorage = localStorage.getItem('isLoggedIn') === 'true';
    setIsLoggedIn(isLoggedInStorage);
    
    if (isLoggedInStorage) {
      try {
        const storedUserData = localStorage.getItem('userData');
        if (storedUserData) {
          setUserData(JSON.parse(storedUserData));
        }
      } catch (error) {
        console.error('解析用户数据失败', error);
      }
    }
  };

  // 导航到登录页面
  const goToLogin = () => {
    navigate('/login');
  };
  
  // 导航到仪表板
  const goToDashboard = () => {
    navigate('/dashboard');
  };
  
  // 处理搜索类型切换
  const handleSearchTypeChange = (type) => {
    setSearchType(type);
    setSearchResults(null); // 清除之前的搜索结果
  };
  
  // 处理搜索输入变化
  const handleSearchInputChange = (e) => {
    setSearchQuery(e.target.value);
  };
  
  // 处理搜索提交
  const handleSearch = async () => {
    if (!searchQuery.trim()) return;
    
    setIsSearching(true);
    setError('');
    
    try {
      if (searchType === 'articles') {
        // 搜索文章
        const searchParams = {
          title: searchQuery,
          type: 1
        };
        const response = await workAPI.searchWorks(searchParams);
        if (response && response.result) {
          setSearchResults({ type: 'articles', data: response.result || [] });
        } else {
          setSearchResults({ type: 'articles', data: [] });
        }
      } else {
        // 搜索用户
        const searchParams = {
          nickName: searchQuery
        };
        const response = await userAPI.searchUsers(searchParams);
        if (response && response.result) {
          setSearchResults({ type: 'users', data: response.result || [] });
        } else {
          setSearchResults({ type: 'users', data: [] });
        }
      }
    } catch (err) {
      console.error('搜索失败:', err);
      setError(`搜索失败，请稍后重试`);
    } finally {
      setIsSearching(false);
    }
  };
  
  // 清除搜索结果，返回主页面
  const clearSearch = () => {
    setSearchQuery('');
    setSearchResults(null);
  };
  
  // 导航到用户页面
  const navigateToUserPage = (userId) => {
    navigate(`/author/${userId}`);
  };
  
  // 导航到发布文章页面
  const goToCreateArticle = () => {
    // 获取当前登录用户的userId
    console.log('要传递的 userId:', userData);
    const currentUserId = userData.userId;
    // 确保有userId才传递
    if (currentUserId) {
      navigate('/create-article', { state: { userId: currentUserId } });
    } else {
      navigate('/create-article');
    }
  };

  return (
    <div className="home-container">
      <header className="home-header">
        <h1 className="clickable" onClick={() => navigate('/')}>Board Demo</h1>
        {isLoggedIn && userData ? (
          <button className="user-button" onClick={goToDashboard}>
            {userData.result?.nickName || '用户中心'}
          </button>
        ) : (
          <button className="login-button" onClick={goToLogin}>登录</button>
        )}
      </header>
      
      {/* 发布文章按钮（仅在用户登录后显示） */}
      {isLoggedIn && (
        <button className="create-article-button" onClick={() => goToCreateArticle()} title="发布文章">
          +
        </button>
      )}
      
      <div className="search-container">
        <div className="search-type-toggle">
          <button 
            className={searchType === 'articles' ? 'active' : ''} 
            onClick={() => handleSearchTypeChange('articles')}
          >
            搜索文章
          </button>
          <button 
            className={searchType === 'users' ? 'active' : ''} 
            onClick={() => handleSearchTypeChange('users')}
          >
            搜索用户
          </button>
        </div>
        
        <div className="search-input-container">
          <input
            type="text"
            value={searchQuery}
            onChange={handleSearchInputChange}
            placeholder={searchType === 'articles' ? '输入文章标题关键词...' : '输入用户昵称关键词...'}
            className="search-input"
          />
          <button 
            className="search-button" 
            onClick={handleSearch}
            disabled={isSearching}
          >
            {isSearching ? '搜索中...' : '搜索'}
          </button>
          
          {searchResults && (
            <button className="clear-search-button" onClick={clearSearch}>
              清除搜索
            </button>
          )}
        </div>
      </div>

      {error && <div className="error-message">{error}</div>}
      
      {/* 搜索结果显示 */}
      {searchResults ? (
        <div className="search-results-container">
          <h2>{searchResults.type === 'articles' ? '文章搜索结果' : '用户搜索结果'}</h2>
          
          {isSearching ? (
            <div className="loading">搜索中...</div>
          ) : searchResults.data.length === 0 ? (
            <div className="no-results">未找到匹配的{searchResults.type === 'articles' ? '文章' : '用户'}</div>
          ) : searchResults.type === 'articles' ? (
            <div className="articles-list">
              {searchResults.data.map(article => (
                <div className="article-card" key={article.workId}>
                  <h3 
                    className="article-title clickable" 
                    onClick={() => navigate(`/article/${article.workId}`)}
                  >
                    {article.title}
                  </h3>
                  <p className="article-description">{article.description || '暂无简介'}</p>
                  <div className="article-meta">
                    <span className="article-time">发布时间：{formatDate(article.createdAt)}</span>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="users-list">
              {searchResults.data.map(user => (
                <div className="user-card" key={user.userInfoId}>
                  <h3 
                    className="user-name clickable" 
                    onClick={() => navigateToUserPage(user.userId)}
                  >
                    {user.nickName || '未设置昵称的用户'}
                  </h3>
                  <p className="user-bio">{user.selfIntro|| '这个用户很神秘，还没有填写个人简介'}</p>
                </div>
              ))}
            </div>
          )}
        </div>
      ) : (
        <div className="articles-container">
          <h2>最新作品</h2>
          
          {loading ? (
            <div className="loading">加载中...</div>
          ) : articles.length === 0 ? (
            <div className="no-articles">暂无文章</div>
          ) : (
            <div className="articles-list">
              {articles.map(article => (
                <div className="article-card" key={article.workId}>
                  <h3 
                    className="article-title clickable" 
                    onClick={() => navigate(`/article/${article.workId}`)}
                  >
                    {article.title}
                  </h3>
                  <p className="article-description">{article.description || '暂无简介'}</p>
                  <div className="article-meta">
                    <span className="article-time">发布时间：{formatDate(article.createdAt)}</span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

export default HomePage;
